import os
import re

def sanitize_filename(filename, replacement='_'):
    """
    清理文件名中的特殊字符，确保在各种操作系统上都能正常使用
    
    Args:
        filename (str): 原始文件名
        replacement (str): 用于替换非法字符的字符，默认为下划线
    
    Returns:
        str: 清理后的文件名
    """
    # Windows禁止的字符: \ / : * ? " < > |
    # 同时替换中文特殊字符，如中文冒号：
    illegal_chars = r'[\\/:*?"<>|\\：\\？\\＊\\“\\”\\＜\\＞\\｜\\·\\，\\；\\‘\\’\\【\\】\\《\\》\\（\\）\\￥\\％\\＃\\＠\\！\\＆\\×\\＋\\－\\＝\\｛\\｝\\［\\］]'
    
    # 替换非法字符
    sanitized = re.sub(illegal_chars, replacement, filename)
    
    # 移除控制字符（ASCII码小于32的字符）
    sanitized = ''.join(char for char in sanitized if ord(char) >= 32)
    
    # 去除首尾空格
    sanitized = sanitized.strip()
    
    # 如果文件名以点开头或结尾，可能会在某些系统上引起问题
    while sanitized.startswith('.'):
        sanitized = sanitized[1:] if len(sanitized) > 1 else '_' + sanitized
    while sanitized.endswith('.'):
        sanitized = sanitized[:-1] if len(sanitized) > 1 else sanitized + '_'
    
    # 确保文件名不为空
    if not sanitized:
        sanitized = 'unnamed_file'
    
    # 限制文件名长度（Windows最大255字符）
    if len(sanitized) > 255:
        name, ext = os.path.splitext(sanitized)
        max_name_length = 255 - len(ext)
        sanitized = name[:max_name_length] + ext
    
    return sanitized

def sanitize_foldername(foldername, replacement='_'):
    """
    清理文件夹名中的特殊字符，确保在各种操作系统上都能正常使用
    
    Args:
        foldername (str): 原始文件夹名
        replacement (str): 用于替换非法字符的字符，默认为下划线
    
    Returns:
        str: 清理后的文件夹名
    """
    # 文件夹名的限制与文件名类似
    return sanitize_filename(foldername, replacement)

def sanitize_path(path, replacement='_'):
    """
    清理完整路径中的特殊字符
    
    Args:
        path (str): 原始路径
        replacement (str): 用于替换非法字符的字符，默认为下划线
    
    Returns:
        str: 清理后的路径
    """
    # 分离路径的目录部分和文件名部分
    dirname, basename = os.path.split(path)
    
    # 如果basename为空，说明path是一个目录
    if not basename:
        # 处理目录名
        sanitized_dirname = sanitize_foldername(os.path.basename(dirname), replacement)
        sanitized_path = os.path.join(os.path.dirname(dirname), sanitized_dirname)
    else:
        # 处理完整路径
        sanitized_dirname = sanitize_foldername(os.path.basename(dirname), replacement) if dirname else ''
        sanitized_basename = sanitize_filename(basename, replacement)
        if dirname:
            parent_dir = os.path.dirname(dirname)
            sanitized_path = os.path.join(parent_dir, sanitized_dirname, sanitized_basename)
        else:
            sanitized_path = sanitized_basename
    
    # 标准化路径分隔符
    sanitized_path = os.path.normpath(sanitized_path)
    
    return sanitized_path

# 测试代码
if __name__ == '__main__':
    # 测试用例
    test_cases = [
        'normal_filename.txt',
        '文件名：包含中文冒号.txt',
        'file<name>with*illegal?chars.txt',
        'file.name.',
        '.hidden_file',
        'file' + chr(10) + 'name.txt',  # 包含控制字符
        'very_long_filename' * 20 + '.txt'  # 超长文件名
    ]
    
    for test_case in test_cases:
        print(f"原始: {test_case}")
        print(f"清理后: {sanitize_filename(test_case)}")
        print("---")